/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package consumo.face.cadastro.converter;

import consumo.entity.Cliente;
import java.util.HashMap;
import java.util.Map;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author Carlos Taschetto
 */
@FacesConverter(forClass=Cliente.class)  
public class ClienteConverter implements Converter{
    
    private static Map<Integer, Cliente> cache = new HashMap<Integer, Cliente>();  

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        System.out.println("ProdutoConverter.getAsObject(): " + value);
        if (value == null || value.isEmpty()) {  
            return null;
        }
        int id = Integer.valueOf(value);
        
        Cliente aux = cache.get(id);
        System.out.println("AUx "+aux);
        return aux;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null  
                && "".equals(value)) 
            return null;
  
        Cliente entity = (Cliente) value;  
        if(entity == null || entity.getId()==null)
            return null;
        cache.put(entity.getId(), entity);
        return String.valueOf(entity.getId());
    }
}
